<?php
class Admin_UserGroupController extends Apps_Controller_Action {

	// Default user_group_id
	const DEFAULT_USER_GROUP_ID = 1;

	public function indexAction() {
		$this->_forward('list');
	}

	public function listAction() {
		$this->actResolve('act_delete',
						  'delete', 'user-group', 'admin', array('id' => $this->_getParam('item_checker')),
						  true);

		$q = $this->_dbAdapter
				  ->select()
				  ->from('user_group')
				  ->where('user_group.id != ?', self::DEFAULT_USER_GROUP_ID);

		$grid = new Apps_Plugin_Grid('userGroup');
		$grid->setTableCaption('List User Group')
			 ->setData($q)
			 ->setTableColumnFormat(array(
			 			array(
			 					'title'   	=> 'Title',
			 					'dataField' => 'title'
			 				),
			 			array(
			 					'title'   	=> 'Group Name',
			 					'dataField' => 'name'
			 				),
			 			array(
			 					'title'   	=> 'Description',
			 					'dataField' => 'description'
			 				),
			 			array(
			 					'title'   	=> 'Created Date',
			 					'dataField' => 'description'
			 				),
					 	array('title'      =>  'Edit',
					 		  'html'       =>  array('<a href="/admin/user-group/edit?id=%s"><i class="icon-edit" title="Sửa" ></i></a>', array('id')),
					 		  'width'	   => '2%'
					 	),
					 	array(
					 			'title'     =>  'Delete',
					 		  	'html'      =>  array('<a href="/admin/user-group/delete?id=%s">
							 		  				 <i class="icon-remove must-confirm" title="Xóa"
							 		  				 data-must-confirm-msg="Xóa nhóm người dùng khỏi hệ thống" ></i></a>',
							 		  				 array('id')),
					 		  	'width'	   	=> '2%'
					 	)
			 		));
		$this->view->grid = $grid;
	}

	public function addAction() {
	    $rq   = $this->_request;
        if($rq->isPost()) {
	        $data['title']  	 = $rq->getParam('group-title');
	        $data['name']  		 = $rq->getParam('group-name');

	        if(!$data['title'] ||  !$data['name']) {
	            $this->_flashMessenger->addMessage('Tên hoặc chức vụ nhóm chưa nhập, vui lòng nhập vào.');
	            $this->goBack();
	        }

			$data['description'] = $rq->getParam('description');
	        $roles 		 		 = $rq->getParam('roles');

	        $tbUserGroup = new M_DbTable_UserGroup();
	        $tbGroupAction = new M_DbTable_GroupAction();

	        //ADD User Group
	        $r = $tbUserGroup->safelyInsert($data);
	        //ADD Role
	        if($r) {
				$this->addGroup($roles, $r);
				$this->_flashMessenger->addMessage(self::$msgAddSuccess);
				$this->_redirect('/admin/user-group/index');
	        }
        	$this->goToActionIndex();
        }
	}


	public function editAction() {
		$rq            = $this->_request;
		$tbUserGroup   = new M_DbTable_UserGroup();
		$tbGroupAction = new M_DbTable_GroupAction();
		$tbUser 	   = new M_DbTable_User();

		// Get data show in Form
		$userGroupId   = $rq->getParam('id');

		if(!$userGroupId || !($dataGroup = $tbUserGroup->fetchRow(array('id = ?' => $userGroupId))->toArray())) {
			$this->_flashMessenger->addMessage(self::$msgNoRecordFound);
			return $this->_redirect('/admin/user-group/index');
		}

		// Group_Default cannot edit
			if($userGroupId == self::DEFAULT_USER_GROUP_ID) {
				$this->_flashMessenger->addMessage('Nhóm người dùng mặc định không được thay đổi');
				return $this->goToActionIndex();
			}

		// Get Roles  to show in checkbox
			$privilege = $tbGroupAction->getListActionFromGroupAction($userGroupId);
		$rolesGroup = $this->getRolesGroup($privilege);
		$this->view->data  = $dataGroup;
		$this->view->roles = $rolesGroup;

		// Create new Group and Delete old Group
		if($rq->isPost()) {
			$oldGroupId 		 = $rq->getParam('id');
			$data['title']  	 = $rq->getParam('group-title');
			$data['name']  		 = $rq->getParam('group-name');
			$data['description'] = $rq->getParam('description');
			$roles 		 		 = $rq->getParam('roles');
	//ADD User Group
	        $r = $tbUserGroup->safelyInsert($data);
	        //ADD Role
	        if($r) {
		        $this->addGroup($roles, $r);

		        // Delete old Group
				$tbUser->safelyUpdate(array('user_group_id' => $r), array('user_group_id = ?' => $oldGroupId));

				$tbUserGroup->safelyDelete(array('id = ?' => $oldGroupId));
				$this->_flashMessenger->addMessage(self::$msgUpdateSuccess);
				$this->_redirect('/admin/user-group/index');
			}
		}

	}

	public function deleteAction() {
		$this->disableLayout(true, true);
		$rq = $this->_request;
		$groupIds = $rq->getParam('id');

		if(!$groupIds) {$this->goToActionIndex();}

		$tbUserGroup   = new M_DbTable_UserGroup();
		$tbGroupAction = new M_DbTable_GroupAction();
		if(is_array($groupIds)) {
			foreach ($groupIds as $groupId) {

				// Group_Default cannot delete
					if($groupId == self::DEFAULT_USER_GROUP_ID) {
						$this->_flashMessenger->addMessage('Nhóm Người dùng quản trị. Không được xóa');
						$this->_redirect('/admin/user-group/index');
					}

				$tbGroupAction->safelyDelete(array('user_group_id = ?' => $groupId));
				$tbUserGroup->safelyDelete(array('id = ?' => $groupId));
			}
			$this->_redirect('/admin/user-group/index');
		} elseif (is_numeric($groupIds)) {

			// Group_Default cannot delete
				if($groupIds == self::DEFAULT_USER_GROUP_ID) {
					$this->_flashMessenger->addMessage('Nhóm Người dùng quản trị. Không được xóa');
					$this->_redirect('/admin/user-group/index');
				}

			$tbGroupAction->safelyDelete(array('user_group_id = ?' => $groupIds));
			$r = $tbUserGroup->safelyDelete(array('id = ?' => $groupIds));
			$this->_flashMessenger->addMessage($r ? self::$msgDeleteSuccess : self::$msgDeleteError);
			$this->_redirect('/admin/user-group/index');
		} else {
			$this->_redirect('/admin/user-group/index');
		}
	}

	public function addGroup($roles, $r) {
		$tbGroupAction = new M_DbTable_GroupAction();
    	// Default Access
    		$actionIds = $tbGroupAction->getActionByModule('default');
    		foreach ($actionIds as $k => $v) {
    			$d['user_group_id'] = $r;
    			$d['acl_action_id'] = $v['id'];
    			$tbGroupAction->safelyInsert($d);
    		}

    		$actionIds = $tbGroupAction->getActionByModule('vct');
    		foreach ($actionIds as $k => $v) {
    			$d['user_group_id'] = $r;
    			$d['acl_action_id'] = $v['id'];
    			$tbGroupAction->safelyInsert($d);
    		}

			// access module Admin
    		$actionIds = $tbGroupAction->getArrayAction('admin', 'index');
    		foreach ($actionIds as $k => $v) {
    			$d['user_group_id'] = $r;
    			$d['acl_action_id'] = $v['id'];
    			$tbGroupAction->safelyInsert($d);
    		}

    		// Login logout
    		$actionIds = $tbGroupAction->getArrayAction('admin', 'auth');
    		foreach ($actionIds as $k => $v) {
    			$d['user_group_id'] = $r;
    			$d['acl_action_id'] = $v['id'];
    			$tbGroupAction->safelyInsert($d);
    		}

// Set Privilige
		foreach ($roles as $value) {
			if($value != 'gallery') {
				$actionIds = $tbGroupAction->getArrayAction('admin', $value);
	        	foreach ($actionIds as $k => $v) {
		        	$d['user_group_id'] = $r;
					$d['acl_action_id'] = $v['id'];
		        	$tbGroupAction->safelyInsert($d);
	        	}

	        	// Photo management
	        	if(($value == 'tour') || ($value == 'cruise') || ($value == 'hotel')) {
	        		$actionPhoto = $tbGroupAction->getAction('admin', 'photo-management', $value);
					$d['user_group_id'] = $r;
					$d['acl_action_id'] = $actionPhoto['id'];
					$tbGroupAction->safelyInsert($d);
	        	}
			} else {
				$actionGalery = $tbGroupAction->getAction('admin', 'photo-management', $value);
				$d['user_group_id'] = $r;
				$d['acl_action_id'] = $actionGalery['id'];
				$a = $tbGroupAction->safelyInsert($d);
			}
        }
	}

	public function getRolesGroup($privilege) {
		$rolesGroup = array();
		foreach ($privilege as $value) {
			if($value['module_name'] == 'admin') {
				switch ($value['controller_name']) {
					case 'tour' :
						$rolesGroup[] = 'tour';
					    break;
					case 'tour-category' :
						$rolesGroup[] = 'tour-category';
					    break;
					case 'tour-style' :
						$rolesGroup[] = 'tour-style';
					    break;
					case 'cruise-itinerary-tour' :
						$rolesGroup[] = 'cruise-itinerary-tour';
					case 'cruise' :
						$rolesGroup[] = 'cruise';
					    break;
					case 'cruise-category' :
						$rolesGroup[] = 'cruise-category';
					    break;
					case 'cruise-type' :
						$rolesGroup[] = 'cruise-type';
					    break;
					case 'cruise-itinerary' :
						$rolesGroup[] = 'cruise-itinerary';
					    break;
					case 'hotel' :
						$rolesGroup[] = 'hotel';
					    break;
					case 'hotel-type' :
						$rolesGroup[] = 'hotel-type';
					    break;
					case 'customer' :
						$rolesGroup[] = 'customer';
					    break;
					case 'order' :
						$rolesGroup[] = 'order';
					    break;
					case 'order-status' :
						$rolesGroup[] = 'order-status';
					    break;
					case 'payment-type' :
						$rolesGroup[] = 'payment-type';
					    break;
					case 'enquire' :
						$rolesGroup[] = 'enquire';
					    break;
					case 'contact' :
						$rolesGroup[] = 'contact';
					    break;
					case 'ckfinder' :
						$rolesGroup[] = 'ckfinder';
					    break;
					case 'event' :
						$rolesGroup[] = 'event';
					    break;
					case 'visa' :
						$rolesGroup[] = 'visa';
					    break;
					case 'faqs' :
						$rolesGroup[] = 'faqs';
					    break;
					case 'faqs-category' :
						$rolesGroup[] = 'faqs-category';
					    break;
					case 'article' :
						$rolesGroup[] = 'article';
					    break;
					case 'country' :
						$rolesGroup[] = 'country';
					    break;
					case 'country-article' :
						$rolesGroup[] = 'country-article';
					    break;
					case 'area' :
						$rolesGroup[] = 'area';
					    break;
					case 'region' :
						$rolesGroup[] = 'region';
					    break;
					case 'area-destination' :
						$rolesGroup[] = 'area-destination';
					    break;
					case 'region-destination' :
						$rolesGroup[] = 'region-destination';
					    break;
					case 'vietnam-travel-destination' :
						$rolesGroup[] = 'vietnam-travel-destination';
					    break;
					case 'vct-info' :
						$rolesGroup[] = 'vct-info';
					    break;
					case 'vct-setting' :
						$rolesGroup[] = 'vct-setting';
					    break;
					case 'photo-management' :
						if($value['action_name'] == 'gallery') {
							$rolesGroup[] = 'gallery';
						}
					    break;
					case 'support' :
						$rolesGroup[] = 'support';
					    break;
					case 'user' :
						$rolesGroup[] = 'user';
					    break;
					case 'user-group' :
						$rolesGroup[] = 'user-group';
					    break;
					case 'ckfinder' :
						$rolesGroup[] = 'ckfinder';
					    break;
				}
			}
		}
			// Filter array : Only use for this $roleGroup()
			$result = array();
			$temp = '';
			for($i = 0; $i < count($rolesGroup); $i++) {
				if($rolesGroup[$i] != $temp) {
					$result[] = $rolesGroup[$i];
					$temp = $rolesGroup[$i];
				}
			}

		return $result;
	}
}
